﻿using BgTransAPI.ControllerHelpers;
using BgTransAPI.Models;
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;

namespace BgTransAPI.Controllers
{
    public class ShedulesController : BaseApiController
    {
        [HttpPost]
        public HttpResponseMessage GetShedules()
        { 
            
            const string CAPTCHAURL = "http://gps.skgt-bg.com/Services/Captcha.ashx";
            const string SHEDULES_URL = "http://gps.skgt-bg.com/Web/SelectByLine.aspx";
            const string REQUEST_BODY = @"__EVENTTARGET=ctl00%24ContentPlaceHolder1%24CaptchaInput&__EVENTARGUMENT=&__LASTFOCUS=&__VIEWSTATE=%2FwEPDwULLTE5ODg1MzQ2ODgPZBYCZg9kFgICAw9kFgICAw9kFgYCAQ9kFhACBQ8QZGQWAQIBZAIJDw9kDxAWAWYWARYCHg5QYXJhbWV0ZXJWYWx1ZQUBMRYBZmRkAgsPEA8WAh4LXyFEYXRhQm91bmRnZBAVXhItLSDQmNC30LHQtdGA0LggLS0BMQEzATQBNQE2ATcBOAE5AjEwAjExAjEyAjE0AjE4AjIwAjIyAjIzAjI0AjI1AjI2AjI3AjI4AjI5AjMwAjMxAjQyAjQ0AjQ1AjQ3AjQ4AjQ5AjU0AjU2AjU5AjYwAjYzAjY0AjY1AjY3AjY5AjcwAjcyAjczAjc0Ajc1Ajc2Ajc3Ajc4Ajc5AjgxAjgyAjgzAjg0Ajg1Ajg2Ajg3Ajg4AjkwAjkzAjk0Ajk4AzEwMAMxMDEDMTAyAzEwNwMxMDgDMTExAzExMwMxMTQDMTE3AzExOAMxMTkDMTIwAzEyMgMxMjMDMTUwAzIwNAMyMTMDMjYwAzI4MAMyODUDMjk0AzMwNQMzMDYDMzA5AzMxMAMzMTQDMzg0AzQwNAM0MTMDNjA0AzdUTQRUTTEyBDQ00JEVXgACNjYCNjgCNjkCNzACNzECNzICNzQBMgI3NQE0AjM4Ajc2AjQxAjQwAjQzAjQ1AjQ2AjQ3AjQ4AzEwNAI0OQI1MAMxMDkC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G93Lm9wZW4oJ2h0dHA6Ly93d3cuYmdtYXBzLmNvbS90ZW1wbGF0ZXMvcmVkaXJlY3RjYXQvc2tndC8wNzQyJywnJylkAgUPDxYCHwMFKdCX0JjQnNCV0J0g0JTQktCe0KDQldCmINCd0JAg0KHQn9Ce0KDQotCQZGQCBw8PFgIfAwWCASLQodCi0KPQlNCV0J3QotCh0JrQmCDQmtCe0JzQn9Cb0JXQmtChOyDQo9CbLiDQkNCa0JDQlC4g0JEuINCh0KLQldCk0JDQndCe0JI7INCf0J7QodCe0JrQkCDQo9CbLiDQn9Cg0J7QpC4g0JDQoi4g0JjQqNCY0KDQmtCe0JIiCjtkZAIHD2QWAgIDDw9kDxAWA2YCAQICFgMWAh8ABQI5NxYCHwAFAjU4FgIfAAUBMRYDZmZmZGQYAwUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFgEFIGN0bDAwJENvbnRlbnRQbGFjZUhvbGRlcjEkaW1nTWFwBSFjdGwwMCRDb250ZW50UGxhY2VIb2xkZXIxJGd2Um91dGUPPCsACQEIAgFkBSFjdGwwMCRDb250ZW50UGxhY2VIb2xkZXIxJGd2VGltZXMPPCsACQEIAgFk3Xm8cMhwBTaEKB1MOOAHl4xxQfE%3D&ctl00%24ContentPlaceHolder1%24ddlTransportType={1}&ctl00%24ContentPlaceHolder1%24ddlLines={2}&ctl00%24ContentPlaceHolder1%24rblRoute={3}&ctl00%24ContentPlaceHolder1%24ddlStops={4}&ctl00%24ContentPlaceHolder1%24CaptchaInput={0}&__EVENTVALIDATION=%2FwEWfgKlo%2B7CDgKv2ZuPBAKv2ZuPBAKgtrHhCAK%2FtrHhCAKhtrHhCAKUwsypBAKUwsypBAKerZ7ECAKercbHCAKercrHCAKdrabECAKdrarECAKdra7ECAKdrZbECAKarebHCAKdrZrECAKYrebHCAKZrcbHCAKdrZ7ECAKYrarECAKYrabECAKYrZLECAKYrZrECAKYrZ7ECAKYrYLECAKYrcbHCAKBkcgmApityscIAp%2BtpsQIAviP8AwCm62SxAgC0NXn5gECma2qxAgC%2BI%2BUDALuq87TDQKBkewmAqT%2B8o0KAoOtxscIApqtrsQIAqT%2B7o0KAp%2Bt5scIApqtmsQIAp6t5scIAp2t5scIAp2tgsQIAp2txscIAp2tyscIAput5scIAvLMkucGAsvChc0LAoytpsQIAoytqsQIAoyt5scIAp%2BtrsQIAp%2BtksQIApqtgsQIAp%2BtlsQIAoOt5scIAoOtyscIAp%2BtmsQIAp%2BtnsQIAputpsQIAoytrsQIAr3sxZMPAputqsQIAp%2BtgsQIApqtxscIApmtrsQIApitlsQIAputrsQIApqtyscIApqtnsQIApmt5scIAsWmwrkOApmtksQIApmtlsQIApmtmsQIApmtnsQIApmtgsQIApmtpsQIAoytksQIAu6rqtANAoytlsQIAoytmsQIAsWm0rkOAp%2BtxscIAtfV5%2BYBAvLMiucGAoytgsQIAoytxscIAp%2BtyscIAp6tpsQIArzswZMPAsvCpc0LAr3swZMPAoOtpsQIAoOtqsQIAsWmyrkOAsvCic0LAoCRyCYCorPx1AQCorPt1AQCtdyjuQgCgrTnzQgCgrTnzQgCj6CvtQgCkqDTUAKQoKOaBwKQoIvACQKSoOekAQKSoPOJCgL2%2BbusBgLb0IHPDgLRkYe4CgK6iKUtAoDeqYgDAuW0picCzqOUjAkCwaPIxggC37Se%2FAwC%2Bt356QICpZqmqQMC4rqpgwoC18exuwcC9vPXoQ7rbUvYMgu4%2BKRvzcsJiZtm3fcrqg%3D%3D";
            var responseMsg = this.PerformOperationAndHandleExceptions(() =>
            {
                // Make Get request to obtain cookie
                WebRequester requester = new WebRequester(SHEDULES_URL, "text/html");
                var responce = requester.PerformGetRequest(null) as HttpWebResponse;
                var cookieContainer = new CookieContainer();
                foreach (Cookie cook in responce.Cookies)
                {
                    cookieContainer.Add(cook);
                }

                // decode captcha
                CaptchaDecoder decode = new CaptchaDecoder(CAPTCHAURL);
                string imageCodeAsString = decode.DecodeJpgImage(cookieContainer);
              
                // make post Request and get shedules as html
                requester.SiteUrl = SHEDULES_URL;
                requester.ContentType = "application/x-www-form-urlencoded";
                var param = new SheduleInputParams();
                var formatedReqBody = String.Format(REQUEST_BODY, imageCodeAsString, param.TransportType, param.Line, param.Route, param.Stop);
                responce = requester.PerformPostRequest(formatedReqBody, cookieContainer) as HttpWebResponse;

                // extract shedules from html responce doc
                using (var responseReader = new StreamReader(responce.GetResponseStream(), Encoding.UTF8))
                {
                    StringBuilder builder = new StringBuilder();
                    builder.Append(responseReader.ReadToEnd());
                    HtmlDataExtractor extractor = new HtmlDataExtractor(builder.ToString());

                    var sheduleResult = new ShedulesResult()
                    {

                        Shedules = extractor.GetShedules(),
                        BusRoute = "СТУДЕНТСКИ ГРАД - СУ КЛИМЕНТ ОХРИДСКИ",
                        BusStationName = "ЗИМЕН ДВОРЕЦ НА СПОРТА"
                        

                    };
                    
                 
                    return this.Request.CreateResponse(HttpStatusCode.OK, sheduleResult);
                 
                }

                
            });

            return responseMsg;
        }
    }
}